package com.sixeco.carservice.modular.device.lock;

/**
 *
 * @author daify
 * @date 2019-06-18 11:59
 **/
public class SynchronizedTest {
    
    private int value = 0;
    
    private Object lock = new Object();

    public Thread getWaitThread () {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取 锁，离开代码块后就释放锁
                synchronized (lock) {
                    try {
                        lock.wait();
                        System.out.println("线程已经停止");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public Thread getNotifyThread () {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取 锁，离开代码块后就释放锁
                synchronized (lock) {
                    // 唤醒一个被等待的线程。
                    lock.notifyAll();
                    System.out.println("线程已经停止");
                }
            }
        });
    }
    
    public Thread getDefThread () {
        return new Thread(new Runnable() {
            @Override
            public void run() {
                // 获取 锁，离开代码块后就释放锁
                synchronized (lock) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    value = value + 1;
                    System.out.println(value);
                }
            }
        });
    }

    /**
     * 同步代码块
     * 此时持有的锁是当前实例对象
     */
    public synchronized void testSync() {
        // do some things
    }

    /**
     * 同步代码块
     * 此时持有的锁是当前对象对应的class对象
     */
    public static synchronized void testClassSync() {
        // do some things
    }


    /**
     * 这种加锁是不起作用的。必须保证锁对象的唯一性
     */
    public void testNonSync() {
        synchronized (new Object()) {
            // do some things
        }
    }
    

    public void defLock () {
        Thread t = getDefThread();
        Thread t2 = getDefThread();
        Thread t3 = getDefThread();
        t.start();
        t2.start();
        t3.start();
    }
    
}
